import React, { useState, useEffect } from 'react';
import markdownit from 'markdown-it';
import emoji from 'markdown-it-emoji';
import codeCopy from 'markdown-it-code-copy';
import hljs from 'highlight.js';
import './index.less';

// 样式用的： https://github.com/sindresorhus/github-markdown-css/blob/main/github-markdown.css


const MarkdownRenderer = ({ markdownText }: any) => {
  const [htmlText, setHtmlText] = useState<string>('');
  useEffect(() => {
    // 创建一个 markdown-it 实例并启用 emoji 插件
    const md = markdownit({
      // Enable HTML tags in source
      html: false,

      // Use '/' to close single tags (<br />).
      // This is only for full CommonMark compatibility.
      xhtmlOut: false,

      // Convert '\n' in paragraphs into <br>
      breaks: false,

      // CSS language prefix for fenced blocks. Can be
      // useful for external highlighters.
      langPrefix: 'language-',

      // Autoconvert URL-like text to links
      linkify: false,

      // Enable some language-neutral replacement + quotes beautification
      // For the full list of replacements, see https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.js
      typographer: false,

      // Double + single quotes replacement pairs, when typographer enabled,
      // and smartquotes on. Could be either a String or an Array.
      //
      // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
      // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
      quotes: '“”‘’',

      // Highlighter function. Should return escaped HTML,
      // or '' if the source string is not changed and should be escaped externally.
      // If result starts with <pre... internal wrapper is skipped.
      highlight(code: any, lang: any) {
        const language = hljs.getLanguage(lang) ? lang : 'plaintext';
        return hljs.highlight(code, { language }).value;
      },
    }).use(codeCopy).use(emoji);
    // 将 markdown-it 处理后的结果设置为组件的状态
    setHtmlText(md.render(markdownText));
  }, [markdownText]);

  return (
    // eslint-disable-next-line react/no-danger
    <div dangerouslySetInnerHTML={{ __html: htmlText }} className="md_preview" />
  );
};

export default MarkdownRenderer;

